var express = require('express');
var router = express.Router();
const shsDB = require("../../db/index.js");
/**添加评论*/
router.post("/addComment", jwtVerify, async function(req, res, next) {
	const bodyItem = req.body; // 获取请求体中的数据
	const userinfo = req.shsImUserInfo; // 获取执行操作的用户信息
	const obj = {
		code: 201, // 默认返回码
		message: "添加评论失败", // 默认消息
		status: false // 默认操作状态
	};

	// 参数校验
	if (!bodyItem.stateId || !bodyItem.content) {
		obj.message = "未按要求传参[stateId, content]";
		res.end(JSON.stringify(obj));
		return;
	}

	// 构造 SQL 语句
	const commentSql = `
    INSERT INTO \`comments\` (\`stateId\`, \`userId\`, \`parentId\`, \`replyUserId\`, \`content\`, \`imageUrls\`, \`createTime\`)
    VALUES (${bodyItem.stateId}, ${userinfo.fromId}, ${bodyItem.parentId || null}, ${bodyItem.replyUserId || null}, '${bodyItem.content}', '${bodyItem.imageUrls || ""}', now());
  `;
	try {
		await shsDB(commentSql);
		obj.code = 200;
		obj.message = "评论添加成功";
		obj.status = true;
		res.send(JSON.stringify(obj));
	} catch (err) {
		obj.message = "数据库操作失败：" + err.message;
		res.send(JSON.stringify(obj));
	}
});
/**
 * 点赞评论
 */
router.post("/likeComment", jwtVerify, async function(req, res, next) {
	const bodyItem = req.body; // 获取请求体中的数据
	const userinfo = req.shsImUserInfo; // 获取执行操作的用户信息

	const obj = {
		code: 201, // 默认返回码
		message: "点赞失败", // 默认消息
		status: false // 默认操作状态
	};

	// 参数校验
	if (!bodyItem.commentId) {
		obj.message = "未按要求传参[commentId]";
		res.end(JSON.stringify(obj));
		return;
	}

	// 构造 SQL 语句
	const likeSql = `
    UPDATE \`comments\`
    SET \`likeCount\` = \`likeCount\` + 1
    WHERE \`commentId\` = ${bodyItem.commentId};
  `;

	try {
		await shsDB(likeSql);
		obj.code = 200;
		obj.message = "点赞成功";
		obj.status = true;
		res.send(JSON.stringify(obj));
	} catch (err) {
		obj.message = "数据库操作失败：" + err.message;
		res.send(JSON.stringify(obj));
	}
});
/**
 * 获取评论列表
 */

/**
 * 获取一级评论（分页）
 */
router.post("/getTopLevelComments", jwtVerify, async function(req, res, next) {
    const bodyItem = req.body;
    const obj = {
        code: 201,
        message: "获取一级评论失败",
        status: false
    };

    if (!bodyItem.stateId) {
        obj.message = "未按要求传参[stateId]";
        res.end(JSON.stringify(obj));
        return;
    }

    const page = bodyItem.page || 1; // 当前页码
    const limit = bodyItem.limit || 10; // 每页显示条数
    const offset = (page - 1) * limit; // 偏移量

    // 获取一级评论及其二级评论数量
    const commentsSql = `
        SELECT 
          c.commentId,
          c.content,
          c.userId,
          c.createTime,
          c.likeCount,
          c.imageUrls,
          u.username AS userName,
          u.url AS userAvatar,
          (SELECT COUNT(*) FROM comments AS c2 WHERE c2.parentId = c.commentId AND c2.isDeleted = 0) AS replyCount
        FROM \`comments\` AS c
        LEFT JOIN \`users\` AS u ON c.userId = u.Id
        WHERE c.stateId = ${bodyItem.stateId} AND c.parentId IS NULL AND c.isDeleted = 0
        ORDER BY c.createTime DESC
        LIMIT ${limit} OFFSET ${offset};
    `;

    // 获取总记录数
    const totalSql = `
        SELECT COUNT(*) AS total
        FROM \`comments\` AS c
        WHERE c.stateId = ${bodyItem.stateId} AND c.parentId IS NULL AND c.isDeleted = 0;
    `;

    try {
        const [comments, totalResult] = await Promise.all([shsDB(commentsSql), shsDB(totalSql)]);
        const total = totalResult[0].total; // 总记录数
        const totalPage = Math.ceil(total / limit); // 总页数

        obj.code = 200;
        obj.message = "获取一级评论成功";
        obj.status = true;
        obj.data = comments;
        obj.total = total; // 总记录数
        obj.currentPage = page; // 当前页码
        obj.pageSize = limit; // 每页显示条数
        obj.totalPage = totalPage; // 总页数
        res.send(JSON.stringify(obj));
    } catch (err) {
        obj.message = "数据库操作失败：" + err.message;
        res.send(JSON.stringify(obj));
    }
});

/**
 * 获取二级评论（分页）
 */
router.post("/getReplyComments", jwtVerify, async function(req, res, next) {
    const bodyItem = req.body;
    const obj = {
        code: 201,
        message: "获取二级评论失败",
        status: false
    };

    // 参数校验
    if (!bodyItem.parentId) {
        obj.message = "未按要求传参[parentId]";
        res.end(JSON.stringify(obj));
        return;
    }

    const page = bodyItem.page || 1; // 当前页码
    const limit = bodyItem.limit || 10; // 每页显示条数
    const offset = (page - 1) * limit; // 偏移量

    // 构造 SQL 语句
    const repliesSql = `
        SELECT 
          c.commentId,
          c.content,
          c.userId,
          c.createTime,
          c.likeCount,
          c.imageUrls,
          u.username AS userName,
          u.url AS userAvatar
        FROM \`comments\` AS c
        LEFT JOIN \`users\` AS u ON c.userId = u.Id
        WHERE c.parentId = ${bodyItem.parentId} AND c.isDeleted = 0
        ORDER BY c.createTime ASC
        LIMIT ${limit} OFFSET ${offset};
    `;

    // 获取总记录数
    const totalSql = `
        SELECT COUNT(*) AS total
        FROM \`comments\` AS c
        WHERE c.parentId = ${bodyItem.parentId} AND c.isDeleted = 0;
    `;

    try {
        const [replies, totalResult] = await Promise.all([shsDB(repliesSql), shsDB(totalSql)]);
        const total = totalResult[0].total; // 总记录数
        const totalPage = Math.ceil(total / limit); // 总页数

        obj.code = 200;
        obj.message = "获取二级评论成功";
        obj.status = true;
        obj.data = replies;
        obj.total = total; // 总记录数
        obj.currentPage = page; // 当前页码
        obj.pageSize = limit; // 每页显示条数
        obj.totalPage = totalPage; // 总页数
        res.send(JSON.stringify(obj));
    } catch (err) {
        obj.message = "数据库操作失败：" + err.message;
        res.send(JSON.stringify(obj));
    }
});
/**
 * 删除评论
 */
router.post("/deleteComment", jwtVerify, async function(req, res, next) {
	const bodyItem = req.body; // 获取请求体中的数据
	const userinfo = req.shsImUserInfo; // 获取执行操作的用户信息

	const obj = {
		code: 201, // 默认返回码
		message: "删除评论失败", // 默认消息
		status: false // 默认操作状态
	};

	// 参数校验
	if (!bodyItem.commentId) {
		obj.message = "未按要求传参[commentId]";
		res.end(JSON.stringify(obj));
		return;
	}

	// 检查用户是否有权限删除该评论
	const checkSql = `
    SELECT \`userId\`
    FROM \`comments\`
    WHERE \`commentId\` = ${bodyItem.commentId};
  `;

	try {
		const checkResult = await shsDB(checkSql);
		if (!checkResult.length) {
			obj.message = "评论不存在";
			res.send(JSON.stringify(obj));
			return;
		}

		const commentUserId = checkResult[0].userId;
		if (commentUserId !== userinfo.fromId) {
			obj.message = "无权限删除该评论";
			res.send(JSON.stringify(obj));
			return;
		}

		// 删除评论
		const deleteSql = `
      UPDATE \`comments\`
      SET \`isDeleted\` = 1
      WHERE \`commentId\` = ${bodyItem.commentId};
    `;

		await shsDB(deleteSql);
		obj.code = 200;
		obj.message = "评论删除成功";
		obj.status = true;
		res.send(JSON.stringify(obj));
	} catch (err) {
		obj.message = "数据库操作失败：" + err.message;
		res.send(JSON.stringify(obj));
	}
});

module.exports = router;